package com.heima.behavior.service.iml;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApBehaviorEntryServiceImpl  implements ApBehaviorEntryService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //判断userId是否为空,
         if (userId !=null){
             Query query = Query.query(Criteria.where("refId").is(userId));
             ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
             if (apBehaviorEntry == null){
                 apBehaviorEntry=new ApBehaviorEntry();
                 apBehaviorEntry.setRefId(userId);
                 apBehaviorEntry.setType((short) 1);
                 mongoTemplate.save(apBehaviorEntry);
             }
             return apBehaviorEntry;
         }
         if (equipmentId != null){
             Query query = Query.query(Criteria.where("refId").is(equipmentId));
             ApBehaviorEntry apBehaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
             if (apBehaviorEntry == null){
                 apBehaviorEntry=new ApBehaviorEntry();
                 apBehaviorEntry.setRefId(equipmentId);
                 apBehaviorEntry.setType((short) 0);
                 mongoTemplate.save(apBehaviorEntry);
             }
             return apBehaviorEntry;
         }
        return null;
    }
}
